package com.linkage.seapeak.activity.user;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Person.PersonSettingActivity;
import com.linkage.jz.bankruptcy.activity.Project.PermissionActivity;
import com.linkage.jz.bankruptcy.activity.Project.ProjectPermissionActivity;
import com.linkage.jz.bankruptcy.bean.MyProInfo;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.seapeak.base.BaseActivity;
import com.linkage.seapeak.base.BaseWhiteActivity;
import com.linkage.seapeak.utils.MenuBottomSheetDialog;
import com.linkage.seapeak.utils.ProfileListBottomSheetDialog;
import com.linkage.seapeak.utils.ToastUtil;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


public class PermissionSettingActivity extends BaseWhiteActivity implements CompoundButton.OnCheckedChangeListener{

    public static final int PERMISSIONSERTTING = 0x3d;
    private MyProInfo proInfo;

    private LinearLayout publicSet;
    private TextView publicSetText;
    private LinearLayout canPublic;
    private TextView canPublicText;
    private Switch closeProject;
    private Switch allowJoin;
    private Switch closeCreditReport;
    private Switch openBbs;
    private Switch allowCreditorEdit;
    private Switch voteProcessShow;
    private Switch voteDetailVisiableToCreditor;
    private RelativeLayout managerSetVisiable;
    private TextView managerSetVisiableText;
    private RelativeLayout creditorSetVisiable;
    private TextView creditorSetVisiableText;
    private LinearLayout sysAutoNoticeRange;
    private TextView sysAutoNoticeRangeText;

    public static void start(Activity context, MyProInfo proInfo) {
        Intent intent = new Intent(context, PermissionSettingActivity.class);
        intent.putExtra("proInfo",new Gson().toJson(proInfo));
        context.startActivityForResult(intent, PERMISSIONSERTTING);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_permission_setting, "权限管理");
        String proJson = getIntent().getStringExtra("proInfo");
        proInfo = new Gson().fromJson(proJson, MyProInfo.class);
        initView();
    }

    private void initView() {
        publicSet = (LinearLayout) findViewById(R.id.public_set);
        publicSetText = (TextView) findViewById(R.id.public_set_text);
        canPublic = (LinearLayout) findViewById(R.id.can_public);
        canPublicText = (TextView) findViewById(R.id.can_public_text);
        closeProject = (Switch) findViewById(R.id.close_project);
        allowJoin = (Switch) findViewById(R.id.allow_join);
        closeCreditReport = (Switch) findViewById(R.id.close_credit_report);
        openBbs = (Switch) findViewById(R.id.open_bbs);
        allowCreditorEdit = (Switch) findViewById(R.id.allow_creditor_edit);
        voteProcessShow = (Switch) findViewById(R.id.vote_process_show);
        voteDetailVisiableToCreditor = (Switch) findViewById(R.id.vote_detail_visiable_to_creditor);
        managerSetVisiable = (RelativeLayout) findViewById(R.id.manager_set_visiable);
        managerSetVisiableText = (TextView) findViewById(R.id.manager_set_visiable_text);
        creditorSetVisiable = (RelativeLayout) findViewById(R.id.creditor_set_visiable);
        creditorSetVisiableText = (TextView) findViewById(R.id.creditor_set_visiable_text);
        sysAutoNoticeRange = (LinearLayout) findViewById(R.id.sys_auto_notice_range);
        sysAutoNoticeRangeText = (TextView) findViewById(R.id.sys_auto_notice_range_text);


        /**********************************************************/
//        publicStatus 项目公开状态有：公开（0）、部分公开（1）、不公开（2）`
        publicSetText.setTag(Integer.parseInt(proInfo.getPublicStatus()));
        publicSetText.setText(((int) publicSetText.getTag()) == 0 ? "全部公开" :
                (((int) publicSetText.getTag()) == 1 ? "部分公开" : "不公开"));
        canPublicText.setTag(proInfo.getPublicSection());
        if("".equalsIgnoreCase(proInfo.getPublicSection()))
        {
            canPublicText.setText("0");
        }else {
            canPublicText.setText(proInfo.getPublicSection().split(",").length + "");
        }

        closeProject.setChecked(proInfo.getClose().equals("true"));
        allowJoin.setChecked(proInfo.getAllowJoin().equals("true"));
        closeCreditReport.setChecked(proInfo.getCloseClaimFiling().equals("true"));
        openBbs.setChecked(proInfo.getOpenDiscussion().equals("true"));
        allowCreditorEdit.setChecked(proInfo.getAllowCreditorsChangInfo().equals("true"));
        voteProcessShow.setChecked(proInfo.getDisplayedInstantly().equals("true"));
        voteDetailVisiableToCreditor.setChecked(proInfo.getCreditorsVisibleDetails().equals("true"));

        if (proInfo.getOpenAdministratorList().equals("true") && proInfo.getOpenAdministratorInfo().equals("true")) {
            managerSetVisiableText.setTag(0);
            managerSetVisiableText.setText("列表和详情可见");
        } else if (proInfo.getOpenAdministratorList().equals("true")) {
            managerSetVisiableText.setTag(1);
            managerSetVisiableText.setText("列表可见");
        } else {
            managerSetVisiableText.setTag(2);
            managerSetVisiableText.setText("全部不可见");
        }

        if (proInfo.getOpenCreditorsList().equals("true") && proInfo.getOpenCreditorsInfo().equals("true")) {
            creditorSetVisiableText.setTag(0);
            creditorSetVisiableText.setText("列表和详情可见");
        } else if (proInfo.getOpenCreditorsList().equals("true")) {
            creditorSetVisiableText.setTag(1);
            creditorSetVisiableText.setText("列表可见");
        } else {
            creditorSetVisiableText.setTag(2);
            creditorSetVisiableText.setText("全部不可见");
        }

        sysAutoNoticeRangeText.setTag(Integer.parseInt(proInfo.getSmsScope()));
        sysAutoNoticeRangeText.setText(((int) sysAutoNoticeRangeText.getTag()) == 0 ? "全部债权人" :
                (((int) sysAutoNoticeRangeText.getTag()) == 1 ? "仅线下债权人" : "关闭"));

        /**********************************************************/


        publicSet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPublicSetDialog();
            }
        });
        canPublic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showProfileListDialog();
            }
        });
        managerSetVisiable.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showManagerSetVisiableDialog();
            }
        });
        creditorSetVisiable.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCreditorSetVisiableDialog();
            }
        });
        sysAutoNoticeRange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSysAutoNoticeRangeDialog();
            }
        });

        closeProject.setOnCheckedChangeListener(this);
//        addMenu(new MenuAction(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//            }
//        }, "完成", 0));
    }

    @Override
    public void finish() {
        setProjectRights();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x11 && resultCode == RESULT_OK && data != null) {
            String str = data.getStringExtra("section");
            proInfo.setPublicSection(str);
            canPublicText.setTag(proInfo.getPublicSection());
            if("".equalsIgnoreCase(proInfo.getPublicSection()))
            {
                canPublicText.setText("0");
            }else {
                canPublicText.setText(proInfo.getPublicSection().split(",").length + "");
                if(proInfo.getPublicSection().split(",").length == 7)
                {
                    publicSetText.setText("全部公开");
                    publicSetText.setTag(0);
                    canPublicText.setTag("0,1,2,3,4,5,6");
                    canPublicText.setText(7 + "");
                }
            }
//            canPublicText.setText(proInfo.getPublicSection().split(",").length + "");
        }
    }

    private void showProfileListDialog() {
        if (((int) publicSetText.getTag()) != 1)
            return;

        Intent intent = new Intent(PermissionSettingActivity.this, ProjectPermissionActivity.class);
        intent.putExtra("info", new Gson().toJson(proInfo));
        startActivityForResult(intent, 0x11);
//        final ProfileListBottomSheetDialog dialog = new ProfileListBottomSheetDialog(PermissionSettingActivity.this);
//        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
//            @Override
//            public void onDismiss(DialogInterface d) {
//                String listStr = dialog.getListString();
//                if (!TextUtils.isEmpty(listStr)) {
//                    canPublicText.setText(listStr.split(",").length + "");
//                    canPublicText.setTag(listStr);
//                } else {
//                    canPublicText.setText("0");
//                    canPublicText.setTag("");
//                }
//
//            }
//        });
//        dialog.show();
    }

    private void showPublicSetDialog() {
        final MenuBottomSheetDialog dialog = new MenuBottomSheetDialog(PermissionSettingActivity.this);
        dialog.addItem(new MenuBottomSheetDialog.DialogMenuItem("全部公开", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                publicSetText.setText("全部公开");
                publicSetText.setTag(0);
                canPublicText.setTag("0,1,2,3,4,5,6");
                canPublicText.setText(7 + "");
                dialog.dismiss();
            }
        }));
        dialog.addItem(new MenuBottomSheetDialog.DialogMenuItem("部分公开", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                publicSetText.setText("部分公开");
                publicSetText.setTag(1);
                canPublicText.setTag("0,1,2");
                canPublicText.setText(2 + "");
                canPublicText.setTag(proInfo.getPublicSection());
                canPublicText.setText(proInfo.getPublicSection().split(",").length + "");
                dialog.dismiss();
            }
        }));
        dialog.addItem(new MenuBottomSheetDialog.DialogMenuItem("不公开", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                publicSetText.setText("不公开");
                publicSetText.setTag(2);
                canPublicText.setTag("0");
                canPublicText.setText(0 + "");
                dialog.dismiss();
            }
        }));
        dialog.show();
    }

    private void showManagerSetVisiableDialog() {
        final MenuBottomSheetDialog dialog = new MenuBottomSheetDialog(PermissionSettingActivity.this);
        dialog.addItem(new MenuBottomSheetDialog.DialogMenuItem("列表和详情可见", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                managerSetVisiableText.setText("列表和详情可见");
                managerSetVisiableText.setTag(0);
                dialog.dismiss();
            }
        }));
        dialog.addItem(new MenuBottomSheetDialog.DialogMenuItem("列表可见", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                managerSetVisiableText.setText("列表可见");
                managerSetVisiableText.setTag(1);
                dialog.dismiss();
            }
        }));
        dialog.addItem(new MenuBottomSheetDialog.DialogMenuItem("全部不可见", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                managerSetVisiableText.setText("全部不可见");
                managerSetVisiableText.setTag(2);
                dialog.dismiss();
            }
        }));
        dialog.show();
    }

    private void showCreditorSetVisiableDialog() {
        final MenuBottomSheetDialog dialog = new MenuBottomSheetDialog(PermissionSettingActivity.this);
        dialog.addItem(new MenuBottomSheetDialog.DialogMenuItem("列表和详情可见", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                creditorSetVisiableText.setText("列表和详情可见");
                creditorSetVisiableText.setTag(0);
                dialog.dismiss();
            }
        }));
        dialog.addItem(new MenuBottomSheetDialog.DialogMenuItem("列表可见", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                creditorSetVisiableText.setText("列表可见");
                creditorSetVisiableText.setTag(1);
                dialog.dismiss();
            }
        }));
        dialog.addItem(new MenuBottomSheetDialog.DialogMenuItem("全部不可见", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                creditorSetVisiableText.setText("全部不可见");
                creditorSetVisiableText.setTag(2);
                dialog.dismiss();
            }
        }));
        dialog.show();
    }

    private void showSysAutoNoticeRangeDialog() {
        final MenuBottomSheetDialog dialog = new MenuBottomSheetDialog(PermissionSettingActivity.this);
        dialog.addItem(new MenuBottomSheetDialog.DialogMenuItem("全部债权人", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sysAutoNoticeRangeText.setText("全部债权人");
                sysAutoNoticeRangeText.setTag(0);
                dialog.dismiss();
            }
        }));
        dialog.addItem(new MenuBottomSheetDialog.DialogMenuItem("仅线下债权人", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sysAutoNoticeRangeText.setText("仅线下债权人");
                sysAutoNoticeRangeText.setTag(1);
                dialog.dismiss();
            }
        }));
        dialog.addItem(new MenuBottomSheetDialog.DialogMenuItem("关闭", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sysAutoNoticeRangeText.setText("关闭");
                sysAutoNoticeRangeText.setTag(2);
                dialog.dismiss();
            }
        }));
        dialog.show();
    }

    /**
     * 设置项目权限
     */
    public void setProjectRights() {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            getToken(null);
            return;
        }
        showProgress();
        String proInfoid= proInfo.getId();
       int iPublicSet = ((int) publicSetText.getTag());
        String  strPublicSection =  ((String) canPublicText.getTag());

        boolean closeProject_f = closeProject.isChecked();
        boolean allowJoin_f = allowJoin.isChecked();
        boolean closeCreditReport_f = closeCreditReport.isChecked();
        boolean openBbs_f = openBbs.isChecked();
        boolean allowCreditorEdit_f = allowCreditorEdit.isChecked();
        boolean voteProcessShow_f = voteProcessShow.isChecked();
        boolean voteDetailVisiableToCreditor_f = voteDetailVisiableToCreditor.isChecked();

        int iTmp = (int) managerSetVisiableText.getTag();
        boolean managerSetVisiableText_f1 = true;
        boolean managerSetVisiableText_f2 = false;
        if((int) managerSetVisiableText.getTag() == 2)
        {
            managerSetVisiableText_f1 = false;
            managerSetVisiableText_f2= false;
        }
        if((int) managerSetVisiableText.getTag() == 1)
        {
            managerSetVisiableText_f1 = true;
            managerSetVisiableText_f2 = false;
        }
        if((int) managerSetVisiableText.getTag() == 0)
        {
            managerSetVisiableText_f1 = true;
            managerSetVisiableText_f2 = true;
        }
        int iTmp1 = (int) creditorSetVisiableText.getTag();
        boolean creditorSetVisiableText_f1 = true;
        boolean creditorSetVisiableText_f2 =false;
        if((int) creditorSetVisiableText.getTag() == 2)
        {
            creditorSetVisiableText_f1 = false;
            creditorSetVisiableText_f2 = false;
        }

        if((int) creditorSetVisiableText.getTag() == 1)
        {
            creditorSetVisiableText_f1 = true;
            creditorSetVisiableText_f2 = false;
        }
        if((int) creditorSetVisiableText.getTag() == 0)
        {
            creditorSetVisiableText_f1 = true;
            creditorSetVisiableText_f2 = true;
        }

        int isysAutoNoticeRangeText = ((int) sysAutoNoticeRangeText.getTag());

        Network.getAPIService()
                .setProjectRights(getUserToken(), proInfoid, iPublicSet, strPublicSection,
                        closeProject_f, allowJoin_f, closeCreditReport_f,
                        openBbs_f, allowCreditorEdit_f, voteProcessShow_f,
                        voteDetailVisiableToCreditor_f,
                        managerSetVisiableText_f1,
                        managerSetVisiableText_f2,
                        creditorSetVisiableText_f1,
                        creditorSetVisiableText_f2,
                        isysAutoNoticeRangeText)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        hideProgress();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onError(null);
                            return;
                        } else {
                            showToast("设置成功", ToastUtil.TOAST_TYPE.SUCCESS);
                            setResult(RESULT_OK);
                            PermissionSettingActivity.super.finish();
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        hideProgress();
                        showToast("设置失败", ToastUtil.TOAST_TYPE.ERROR);
                        PermissionSettingActivity.super.finish();
                    }
                });
    }

    PublicNoticeDialog mDialog;

    @Override
    public void onCheckedChanged(CompoundButton buttonView, final boolean isChecked) {
        mDialog = new PublicNoticeDialog(PermissionSettingActivity.this, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeProject.setOnCheckedChangeListener(null);
                if (v.getId() == R.id.btn_save_notice) {
                } else if (v.getId() == R.id.btn_chancel_notice) {
                    closeProject.setChecked(!isChecked);
                }
                closeProject.setOnCheckedChangeListener(PermissionSettingActivity.this);
                if (mDialog != null && mDialog.isShowing())
                    mDialog.dismiss();
            }
        }, 1, "提示", closeProject.isChecked() ? "关闭项目后仅管理人团队负责人和管理员可见，其他人均不可见" :
                "取消关闭项目后项目成员均可见，在公开项目中可查询",
                "否", "是");
        mDialog.show();
    }
}
